package com.uton.rfidcontroller.view.activity.scan;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.uton.rfidcontroller.R;
import com.uton.rfidcontroller.common.GlobalConstants;
import com.uton.rfidcontroller.common.intent.IntentBuilder;
import com.uton.rfidcontroller.common.rfid.UfhData;
import com.uton.rfidcontroller.common.utils.LogUtil;
import com.uton.rfidcontroller.common.utils.SharedPreferencesUtils;
import com.uton.rfidcontroller.common.utils.Utils;
import com.uton.rfidcontroller.databinding.ActivityScanBinding;
import com.uton.rfidcontroller.model.CarDealerListModel;
import com.uton.rfidcontroller.model.CarDealerPatrolDetailModel;
import com.uton.rfidcontroller.model.CheckStateToCommitModel;
import com.uton.rfidcontroller.view.activity.CarDealerDetailActivity;
import com.uton.rfidcontroller.view.activity.SettingActivity;
import com.uton.rfidcontroller.view.adapter.scan.OriRVAdapter;
import com.uton.rfidcontroller.view.base.BaseActivity;
import com.uton.rfidcontroller.viewmodel.activity_model.ScanActivityViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import io.reactivex.ObservableTransformer;

/**
 * Created by 王家宝 on 2017/9/12.
 * Email:639586819@qq.com
 * Tel:18241150668
 */

public class ScanActivity extends BaseActivity<ActivityScanBinding, ScanActivityViewModel> {
    private Timer timer;
    private boolean isCanceled = true;
    private boolean Scanflag = false;
    private static final int SCAN_INTERVAL = 10;
    private Map<String, Integer> data;
    private Handler mHandler;

    @BindView(R.id.rv_scan_ori)
    RecyclerView mRecyclerView;

    private List<CarDealerPatrolDetailModel> mTempData;
    private OriRVAdapter mAdapter;

    public static final int NO_CHECK_COMPLETE = 0;

    /**
     * 存储当前点击开始扫描的时间戳
     */
    private String mCurrentTimeStamp;
    private ArrayList<String> mIdList;


    @Override
    protected int setLayout() {
        return R.layout.activity_scan;
    }

    @Override
    protected void inject() {
        getBinding().setScanModel(getViewModel());
    }

    @Override
    protected String setTitle() {
        return getString(R.string.ui_title_scan);
    }

    @Override
    protected void doSomething() {
//        mTempData = new ArrayList<>();
//        for (int i = 0; i < 50; i++) {
//            CarDealerPatrolDetailModel model = new CarDealerPatrolDetailModel();
//            model.setPlateNumber("GG了" + i);
//            if (i == 20) {
//                model.setRfidLabelId("E2005139700101232510152A");
//            } else if (i == 46) {
//                model.setRfidLabelId("E20051397001010625701101");
//            } else {
//                model.setRfidLabelId("ABCDEFG" + i);
//            }
//
//            mTempData.add(model);
//        }
    }

    @Override
    protected ScanActivityViewModel setViewModel() {
        return new ScanActivityViewModel(
                getIntent().getStringExtra(GlobalConstants.EXTRA_STRING_PARAM1),
                getIntent().getStringExtra(GlobalConstants.EXTRA_STRING_PARAM2)) {
            @Override
            public void showDialog() {
                showProgressDialog(null, false);
            }

            @Override
            public void dismissDialog() {
                disDialog();
            }

            @Override
            public void doOnRefreshSuccess(List<CarDealerListModel> tResponse) {

            }

            @Override
            public void doOnRefreshError() {

            }

            @Override
            public void doOnLoadMoreSuccess(List<CarDealerListModel> tResponse) {

            }


            @Override
            public void doOnLoadMoreError() {

            }

            @Override
            public ObservableTransformer setObservable() {
                return compose(bindToLifecycle());
            }

            @Override
            public void beginScan() {
                scan();
            }

            @Override
            public void beginInit() {
                //设置适配器
                mAdapter = new OriRVAdapter(ScanActivity.this);
                mRecyclerView.setAdapter(mAdapter);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(ScanActivity.this));

                mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                            case GlobalConstants.CODE_COMPLETE:
                                mAdapter.notifyDataSetChanged();
                                break;
                        }
                    }
                };
            }

            @Override
            public void doOnComplete() {
                disDialog();
            }

            @Override
            public void doOnRequestComplete(List<CarDealerPatrolDetailModel> data) {
                mTempData = data;
                mAdapter.setDataList(data);
                if (mIdList == null) {
                    mIdList = new ArrayList<>();
                } else {
                    mIdList.clear();
                }
                for (int i = 0; i < mTempData.size(); i++) {
                    String rfidLabelId = mTempData.get(i).getRfidLabelId();
                    mIdList.add(rfidLabelId);
                }

            }

            @Override
            public boolean checkState() {
                if (mTempData != null) {
                    for (CarDealerPatrolDetailModel model : mTempData) {
                        if (model.getCurrentState() == NO_CHECK_COMPLETE) {
                            return false;
                        }
                    }
                    return true;
                } else {
                    return false;
                }
            }

            @Override
            public void showCheckErrorMsg() {
                Utils.showShortToast("请录入所有的巡检结果");
            }

            @Override
            public List getCurrentCheckStateList() {
                List<CheckStateToCommitModel> tempList = new ArrayList<>();
                for (CarDealerPatrolDetailModel model : mTempData) {
                    CheckStateToCommitModel commitModel = new CheckStateToCommitModel();
                    commitModel.setCarId(model.getCarId());
                    commitModel.setDealerId(getIntent().getStringExtra(GlobalConstants.EXTRA_STRING_PARAM1));
                    //巡检人
                    commitModel.setPatrolAccountId(SharedPreferencesUtils.getUserID());
                    //设置时间戳
                    commitModel.setPatrolTimeStart(mCurrentTimeStamp != null ? mCurrentTimeStamp : Utils.getCurrentTimeStamp());
                    //设置巡检车辆状态
                    commitModel.setCarPatrolState(model.getCurrentState());
                    //设置巡检失败说明
                    commitModel.setFailureReason(model.getErrorMsg());
                    //添加数据
                    tempList.add(commitModel);
                }
                return tempList;
            }

            @Override
            public void doOnCommitSuccess() {
                setResult(GlobalConstants.RESULT_COMMIT_SUCCESS);
                finish();
            }

            @Override
            public void doOnCommitError() {

            }

            @Override
            public void doOnCommitComplete() {

            }

            @Override
            public void showCarDealerDetail() {
                startActivity(new IntentBuilder().from(ScanActivity.this, CarDealerDetailActivity.class).
                        setStringParam(GlobalConstants.EXTRA_STRING_PARAM1, getIntent().
                                getStringExtra(GlobalConstants.EXTRA_STRING_PARAM1)).getIntent());
            }
        };
    }

    private void scan() {
        if (mTempData != null) {
            if (!UfhData.isDeviceOpen()) {
                Utils.showShortToast(getString(R.string.toast_not_open_device));
                startActivity(new IntentBuilder().from(ScanActivity.this, SettingActivity.class).getIntent());
                return;
            }

            mCurrentTimeStamp = Utils.getCurrentTimeStamp();

            if (timer == null) {
                ///////////声音开关初始化
                UfhData.Set_sound(true);
                UfhData.SoundFlag = false;
                //////////
//            if (myAdapter != null) {
//                if(mode.equals(MainActivity.TABLE_6B)){
//                    UfhData.scanResult6b.clear();
//                }else if(mode.equals(MainActivity.TABLE_6C)){
//
//                }
//                myAdapter.mList.clear();
//                myAdapter.notifyDataSetChanged();
//                mHandler.removeMessages(MSG_UPDATE_LISTVIEW);
//                mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW);
//            }

                UfhData.scanResult6c.clear();

                isCanceled = false;
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (Scanflag) {
                            return;
                        }
                        Scanflag = true;
                        UfhData.read6c();
                        data = UfhData.scanResult6c;

                        for (String s : data.keySet()) {
                            for (CarDealerPatrolDetailModel model : mTempData) {
                                if (model.getCurrentState() != GlobalConstants.SCAN_ALREADY) {
                                    if (s.equals(model.getRfidLabelId())) {
                                        //匹配上了ID
                                        model.setCurrentState(GlobalConstants.SCAN_ALREADY);
                                        model.setLocked(true);
                                        mHandler.sendEmptyMessage(GlobalConstants.CODE_COMPLETE);
                                        LogUtil.d("匹配成功");
                                    }
                                }
                            }
                        }

                        LogUtil.d(Thread.currentThread().getName());
//
//                    mHandler.removeMessages(MSG_UPDATE_LISTVIEW);
//                    mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW);
                        Scanflag = false;
                    }
                }, 0, SCAN_INTERVAL);
                getViewModel().scanState.set(Utils.getString(R.string.ui_stop_scan));
            } else {
                //cancelScan();
                isCanceled = true;
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                    getViewModel().scanState.set(Utils.getString(R.string.ui_begin_scan));
                }
                UfhData.Set_sound(false);
            }


        } else {
            Utils.showShortToast("当前没有数据");
        }


    }

    private void cancelScan() {
        isCanceled = true;
        if (timer != null) {
            timer.cancel();
            timer = null;
            getViewModel().scanState.set(Utils.getString(R.string.ui_begin_scan));
            UfhData.scanResult6c.clear();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        UfhData.Set_sound(false);
        cancelScan();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case GlobalConstants.RESULT_SAVE_RET:
                int pos = data.getIntExtra(GlobalConstants.EXTRA_INT_PARAM1, -1);
                if (pos != -1) {
                    mTempData.get(pos).setErrorMsg(data.getStringExtra(GlobalConstants.EXTRA_STRING_PARAM1));
                    mTempData.get(pos).setCurrentState(GlobalConstants.SCAN_ERROR);
                    mAdapter.notifyDataSetChanged();
                } else {
                    LogUtil.d(getString(R.string.log_error_data));
                }
                break;
        }

    }
}
